package com.myk.game.gobangchess.ai.startzone;

import java.util.Arrays;

public class SelectionAlgorithm {

    public static int[][] selection(int[][] population, int[] fitness) {
        double[] adjustedFitness = new double[fitness.length];
        int minFitness = Arrays.stream(fitness).min().orElse(0);
        double totalAdjustedFitness = 0;

        for (int i = 0; i < fitness.length; i++) {
            adjustedFitness[i] = fitness[i] - minFitness + 1;
            totalAdjustedFitness += adjustedFitness[i];
        }

        double[] probabilities = new double[fitness.length];
        for (int i = 0; i < adjustedFitness.length; i++) {
            probabilities[i] = adjustedFitness[i] / totalAdjustedFitness;
        }

        int[][] selectedIndices = population;
        for (int i = 0; i < fitness.length; i++) {
            double randomNum = Math.random();
            double sum = 0;
            for (int j = 0; j < probabilities.length; j++) {
                sum += probabilities[j];
                if (randomNum <= sum) {
                    selectedIndices[i] = population[j];
                    break;
                }
            }
        }

        return selectedIndices;
    }

    public static void main(String[] args) {
        int[][] population = {{1, 2, 3, 4},
                                {1,0,0,0},
                                {0,1,0,0},
                                {0,0,0,1}};
        int[] fitness = {8, 12, 14, 16};
        int[][] selectedIndices = selection(population, fitness);

        System.out.println("Selected Indices:");
            System.out.println(selectedIndices);

    }
}
